﻿using MediatR;
using PoemGame.Domain.GameAggregate.Events;
using PoemGame.Domain.Seedwork;
using PoemGame.Events.Shared;

namespace PoemGame.Events.MediatR
{
    public class OutBoundEventBus:IOutBoundEventBus
    {
        private readonly IMediator _mediator;

        public OutBoundEventBus(IMediator mediator)
        {
            _mediator = mediator;
        }

        public async Task PublishAsync(BaseEventDataOutBound data)
        {
            if (data is GameFinishEventDataOutBound finishData)
            {
                await PublishAsync<GameFinishEventDataOutBound>(finishData);
            }
            else if (data is GamePlayEventDataOutBound playData)
            {
                await PublishAsync<GamePlayEventDataOutBound>(playData);
            }
            else if (data is PlayerJoinGameEventDataOutBound joinData)
            {
                await PublishAsync<PlayerJoinGameEventDataOutBound>(joinData);
            }
            else if (data is PlayerLeaveGameEventDataOutBound leaveData)
            {
                await PublishAsync<PlayerLeaveGameEventDataOutBound>(leaveData);
            }
        }

        private async Task PublishAsync<T>(T data) where T : BaseEventDataOutBound
        {
            var eventdata = new OutBoundEvent<T>(data);
            await _mediator.Publish(eventdata);
        }
    }
}
